package com.neulogistics.contrib.procuredcenter.api.application.command.handler;

import com.blackto.lib.mediat.unicast.IRequestHandler;

import com.neulogistics.contrib.procuredcenter.api.application.command.PurchaseCommand;
import com.neulogistics.contrib.procuredcenter.domain.model.aggregate.Goods;
import com.neulogistics.contrib.procuredcenter.domain.model.aggregate.PurchaseOrder;
import com.neulogistics.contrib.procuredcenter.domain.model.enumeration.PurchaseType;
import com.neulogistics.contrib.procuredcenter.domain.model.valueobject.PurchaseItem;
import com.neulogistics.contrib.procuredcenter.domain.repository.IGoodsRepository;
import com.neulogistics.contrib.procuredcenter.domain.repository.IPurchaseOrderRepository;
import com.neulogistics.infrastructure.cache.idservice.RedisIdUtil;
import com.neulogistics.infrastructure.common.serviceresult.BaseResponse;
import com.neulogistics.infrastructure.common.serviceresult.ErrorCode;
import com.neulogistics.infrastructure.common.serviceresult.ResultUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class PurchaseCommandHandler implements IRequestHandler<PurchaseCommand, BaseResponse<Boolean>> {
    @Resource
    IPurchaseOrderRepository purchaseOrderRepository;

    @Resource
    IGoodsRepository goodsRepository;

    @Resource
    RedisIdUtil redisIdUtil;

    private final String PurchaseOrder_Id_Key;

    public PurchaseCommandHandler(@Value("${spring.application.name}") String appName) {
        PurchaseOrder_Id_Key = appName + ":" + "PurchaseOrderId";
    }

    @Override
    public BaseResponse<Boolean> handle(PurchaseCommand command) {
        // 创建采购单
        Long purchaseOrderId = redisIdUtil.nextId(PurchaseOrder_Id_Key);
        Goods goods = goodsRepository.findById(command.goodsId);
        if(goods == null){
            return ResultUtils.error(ErrorCode.NOT_FOUND_ERROR);
        }

        PurchaseItem purchaseItem = new PurchaseItem(goods.getGoodsId(), goods.getGoodsName(),
                goods.getGoodsPrice(), command.count, goods.getMeasureUnit(),
                goods.getVendorInfo().getVendorId(), goods.getVendorInfo().getVendorName());

        PurchaseOrder purchaseOrder = new PurchaseOrder(purchaseOrderId, PurchaseType.Purchase, command.warehouseId, purchaseItem);

        purchaseOrderRepository.save(purchaseOrder);

        return ResultUtils.success(Boolean.TRUE);
    }
}
